package util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexUtils {

	public static String[] findFirstOfGroup(String regex, String input) throws Exception {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(input);
		
		if (matcher.find()) {
			String[] result = new String[matcher.groupCount()];
			for (int i = 0; i < result.length; i++) {
				result[i] = matcher.group(i+1); 
			}
			return result;
		} else {
			throw new Exception("NO MATCH");
		}
	}
	
	public static Pattern getPattern(String regex) {
		return Pattern.compile(regex);
	}
	
	public static Pattern getPatternCaseInsensitive(String regex) {
		return Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
	}
	
	public static List<String> findallSingleGroupWithPattern(Pattern pattern, String input) {
		List<String> result = new ArrayList<String>();
		Matcher matcher = pattern.matcher(input);
		while (matcher.find()) {
			result.add(matcher.group(1)); 
		}
		return result;
	}
	
	public static String[] findFirstOfGroupWithPattern(Pattern pattern, String input) {
		Matcher matcher = pattern.matcher(input);
		
		if (matcher.find()) {
			String[] result = new String[matcher.groupCount()];
			for (int i = 0; i < result.length; i++) {
				result[i] = matcher.group(i+1); 
			}
			return result;
		} else {
			return null;
		}
	}

	public static List<String[]> findallOfGroupWithPattern(Pattern pattern, String input) {
		Matcher matcher = pattern.matcher(input);
		List<String[]> result = new ArrayList<String[]>();
		
		while (matcher.find()) {
			String[] matchStrings = new String[matcher.groupCount()];
			for (int i = 0; i < matchStrings.length; i++) {
				matchStrings[i] = matcher.group(i+1);
			}
			result.add(matchStrings);
		}
		return result;
	}
	
	public static String findSingleMatchWithPattern(Pattern pattern, String input) {
		Matcher matcher = pattern.matcher(input);
		if (matcher.find()) {
			return matcher.group(1); 
		} else {
			return null;
		}
	}

	
	
}
